package utils;

import book.PairOfUidAndBookId;
import com.bit.utils.FileUtils;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 殇
 * Date: 2025-07-21
 * Time: 21:34
 */
public class AnalyingBorrowBook {

    //读取借阅信息
    public PairOfUidAndBookId[] loadObject(String fileName){
        String content=FileUtils.readFile(fileName);
        if(content==null||content.isEmpty()){
            System.out.println("数据不存在");
            return null;
        }
        //拿到每条借阅信息
        String[] s=content.split("\n");
        PairOfUidAndBookId[] pairOfUidAndBookId=new PairOfUidAndBookId[s.length];
        for(int i=0;i<s.length;i++){
            //将每条信息构造成PairOfUidAndBookId类对象
            String[] tmp=s[i].split(",");
            pairOfUidAndBookId[i]=new PairOfUidAndBookId(Integer.parseInt(tmp[0]),Integer.parseInt(tmp[1]));
        }
        return pairOfUidAndBookId;

    }
    //存储借阅信息
    public void storeObject(PairOfUidAndBookId[] pairOfUidAndBookIds,String fileName){
        StringBuilder str=new StringBuilder();
        int n=0;
        //统计实际大小
        for(int i=0;i<pairOfUidAndBookIds.length;i++){
            if(pairOfUidAndBookIds[i]!=null)
                n++;
        }
        for(int i=0;i<n;i++){
            if(pairOfUidAndBookIds[i]!=null) {
                //借阅信息序列化
                str.append(pairOfUidAndBookIds[i].toJson());
                if (i != pairOfUidAndBookIds.length - 1)
                    str.append("\n");
            }
        }
        FileUtils.writeFile(str.toString(),fileName);
    }



}
